<template>
  <el-form>
    <el-form-item label="姓名">
      <el-input v-model.trim="uid_newName.name" />
    </el-form-item>
    <el-form-item label="头像">
      <div>(只能上传jpg/png文件，且不超过10MB)</div>
      <el-upload
        class="avatar-uploader"
        :action="uploadAction"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        name="img"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  props: {
    user: {
      default: () => {
        return {
          uid: '',
          name: '',
          avatar: '',
          password: ''
        }
      }
    }
  },
  data() {
    return {
      uploadAction: process.env.VUE_APP_BASE_API + '/user/upload',
      uid_newName: {
        uid: this.user.uid,
        name: this.user.name
      },
      uid_newAvatar: {
        uid: this.user.uid,
        avatar: this.user.avatar
      },
      imageUrl: ''
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/PNG'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 格式或者 PNG 格式 !')
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB !')
      }
      return (isPNG || isJPG) && isLt10M
    },
    handleAvatarSuccess(res) {
      // res为后端返回的图片地址，将地址设置给imageUrl用于显示
      this.uid_newAvatar.avatar = res
      this.$store.state.user.avatar = res
      this.$store.dispatch('user/putavatar', this.uid_newAvatar).then(() => {
        this.$message({
          message: '头像更新成功！',
          type: 'success',
          duration: 5 * 1000
        })
      })
    },
    submit() {
      this.$store.dispatch('user/submit', this.uid_newName).then(() => {
        this.$message({
          message: '用户信息更新成功，请刷新网页以查看',
          type: 'success',
          duration: 5 * 1000
        })
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
